package com.hhf.feiojcommonservice;

import cn.hutool.json.JSONUtil;
import com.hhf.feiojcommonservice.model.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;

import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author hhf
 * @Date 2024/11/6
 * @Description
 */
public class MainApplication {

    String key = "hhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhfhhf";

    private SecretKey secretKey = new SecretKeySpec(key.getBytes(), SignatureAlgorithm.HS256.getJcaName());

    @Test
    void testJWT() {

        //1. 生成token

//        String content = "Hello World";
        User user = new User();
        user.setId(1L);
        user.setAccount("123");
        user.setPassword("456");


        String content = JSONUtil.toJsonStr(user);

        Map<String, Object> map = new HashMap<>();
        map.put("body",content);

        String jwt = Jwts.builder()
                .signWith(secretKey)
                .claims()
                .add(map)
                .and()//设置主题(声明信息)//设置密钥
                .compact();     //生成签名

        System.out.println(jwt);

        //2. 验证token是否正确
        try {

            //改变jwt,使之解析错误
//            jwt = "我修改了jwt";

            Jwts.parser()
                    .verifyWith(secretKey)
                    .build()
                    .parseSignedClaims(jwt);
            System.out.println("验证 success");
        } catch (JwtException e) {
            System.out.println("验证 fail");
        }


        //2. 解析token
        Claims payload = Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(jwt)
                .getPayload();

        System.out.println(payload);

    }
}
